﻿using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Text;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string[,] Categories = { { "----Chọn Chuyên Mục----", "" }, { "Xã hội", "http://vnexpress.net/gl/xa-hoi/" }, { "Thế giới", "http://vnexpress.net/gl/the-gioi/" }, { "Kinh doanh", "http://vnexpress.net/gl/kinh-doanh/" }, { "Văn hóa", "http://vnexpress.net/gl/van-hoa/" }, { "Thể thao", "http://vnexpress.net/gl/the-thao/" }, { "Pháp luật", "http://vnexpress.net/gl/phap-luat/" }, { "Đời sống", "http://vnexpress.net/gl/doi-song/" }, { "Khoa Học", "http://vnexpress.net/gl/khoa-hoc/" }, { "Vi tính", "http://vnexpress.net/gl/vi-tinh/" }, { "Ô tô - Xe máy", "http://vnexpress.net/gl/oto-xe-may/" }, { "Cười", "http://vnexpress.net/gl/cuoi/" } };
            for (int i = 0; i < Categories.GetLength(0); i++)
            {
                ddlCategory.Items.Add(new ListItem(Categories[i, 0], Categories[i, 1]));
            }
        }
    }

    // Su kien Submit dua du lieu vao DB
    protected void btnSubmit_OnClick(object sender, EventArgs e)
    {
        if (txtTitle.Text != "" && txtDescription.Text != "" && FreeTextBoxContent.Text != "")
        {
            SqlDataSource1.InsertParameters["CHUYENMUC"].DefaultValue = ddlCategory.SelectedItem.Text;
            SqlDataSource1.InsertParameters["TIEUDE"].DefaultValue = txtTitle.Text;
            SqlDataSource1.InsertParameters["MOTA"].DefaultValue = txtDescription.Text;
            SqlDataSource1.InsertParameters["NOIDUNG"].DefaultValue = FreeTextBoxContent.Text;
            SqlDataSource1.InsertParameters["NGAYPOST"].DefaultValue = DateTime.Now.ToString();
            SqlDataSource1.Insert();
            Response.Write("<script>alert('Đã cập nhật cơ sỡ dữ liệu thành công')</script>");
            txtTitle.Text = "";
            txtDescription.Text = "";
            FreeTextBoxContent.Text = "";
        }
        else
            Response.Write("<script>alert('Vui lòng nhập đầy đủ thông tin')</script>");

    }

    // Su kien chon List Topic
    protected void ddlTopic_OnSelectedIndexChanged(Object Source, EventArgs e)
    {
        if (ddlTopic.SelectedIndex != -1 && ddlTopic.SelectedItem.Value != "")
        {
            string Content = GetWebContent(ddlTopic.SelectedItem.Value);
            txtTitle.Text = GetTitle(Content);
            txtDescription.Text = GetDescription(Content);
            InsertSpecialChar(ref Content);
            FreeTextBoxContent.Text = GetContent(Content);
        }
    }
    public string GetWebContent(string strLink)
    {
        string strContent = "";
        try
        {
            WebRequest objWebRequest = WebRequest.Create(strLink);
            objWebRequest.Credentials = CredentialCache.DefaultCredentials;
            WebResponse objWebResponse = objWebRequest.GetResponse();
            Stream receiveStream = objWebResponse.GetResponseStream();
            StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8);
            strContent = readStream.ReadToEnd();
            objWebResponse.Close();
            readStream.Close();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        return strContent;
    }

    // Lay Tieu De
    public string GetTitle(string Content)
    {
        string pattern = "<H1 class=Title>[^<]+";
        Regex Title = new Regex(pattern);
        Match m = Title.Match(Content);
        if (m.Success)
            return m.Value.Substring(16, m.Value.Length - 16);
        return "";
    }

    // Lay Mo Ta
    public string GetDescription(string Content)
    {
        //string pattern = "<H2 class=Lead>[^<]+";
        string pattern = "ion\" content=\"[^\"]+";
        Regex Description = new Regex(pattern);
        Match m = Description.Match(Content);
        if (m.Success)
            return m.Value.Substring(14, m.Value.Length - 14);
        return "";
    }

    // Chen ki tu dat biet vao de Regex lay Lay Noi dung bai viet
    public void InsertSpecialChar(ref string Content)
    {
        int index;
        StringBuilder sb = new StringBuilder(Content);
        index = Content.IndexOf("</STRONG></P>") + 14; // "</STRONG></P>" co do dai 14 ki tu
        sb.Insert(index, "~"); // chen ki tu ~        
        Content = sb.ToString();
    }

    // Lay Noi dung bai viet
    public string GetContent(string Content)
    {
        string pattern = "<H2 class=Lead>+[^~]+";
        Regex regxContent = new Regex(pattern);
        Match m = regxContent.Match(Content);
        Content = m.Value.Substring(15, m.Value.Length - 15);
        Content = m.Value.ToString();
        FixImgageLink(ref Content);
        FixTopicLink(ref Content);
        return Content;
    }

    // Sua link Anh bai viet trong Noi Dung
    public void FixImgageLink(ref string Strfix)
    {
        int index;
        StringBuilder sb = new StringBuilder(Strfix);
        while (Strfix.IndexOf("=\"/Files/") != -1)
        {
            index = Strfix.IndexOf("\"/Files/") + 1; // +1 de tranh lap vo han
            sb.Insert(index, "http://vnexpress.net");
            Strfix = sb.ToString();
        }
    }

    // Sua link bai viet khac
    public void FixTopicLink(ref string Strfix)
    {
        int index;
        StringBuilder sb = new StringBuilder(Strfix);
        while (Strfix.IndexOf("=\"/gl/") != -1)
        {
            index = Strfix.IndexOf("\"/gl/") + 1; // +1 de tranh lap vo han
            sb.Insert(index, "http://vnexpress.net");
            Strfix = sb.ToString();
        }
    }

    // Lay Title va Link cua Topic
    public string[,] GetTitleAndLinkofTopic(String CategoryContent)
    {
        string[,] temp;

        // regex Top news Title
        string patternTopNewsTitle = "link-topnews\">[^<]+";
        Regex TopNewsTitle = new Regex(patternTopNewsTitle);
        Match m1 = TopNewsTitle.Match(CategoryContent);

        // regex Top news Link
        string patternTopNewsLink = @"/gl/(\w+|-)+/(\w+|-)+/(\d|/)+(\w|-)+/";
        patternTopNewsLink += "\" class=\"link-topnews\">";
        Regex TopNewsLink = new Regex(patternTopNewsLink);
        Match m2 = TopNewsLink.Match(CategoryContent);

        // regex Title
        string patternTopicTitle = "link-title\">[^<]+";
        Regex TopicTitle = new Regex(patternTopicTitle);
        MatchCollection mc1 = TopicTitle.Matches(CategoryContent);

        // regex Link title
        string patternTopicLink = @"/gl/(\w+|-)+/(\w+|-)+/(\d|/)+(\w|-)+/";
        patternTopicLink += "\" class=\"link-title\">";
        Regex TopicLink = new Regex(patternTopicLink);
        MatchCollection mc2 = TopicLink.Matches(CategoryContent);

        // Dem So luong Topic
        int count;
        if (mc1.Count > 14) count = 14;
        else count = mc1.Count;
        temp = new string[count + 2, 2];

        temp[0, 0] = "----Chọn Tin----";
        temp[0, 1] = "";
        // Gan topnews vao ListTopic
        temp[1, 0] = m1.Value.Substring(14, m1.Value.Length - 14);
        temp[1, 1] = "http://vnexpress.net" + m2.Value.Substring(0, m2.Value.Length - 23);

        // Gan list Title vao mang
        for (int i = 0; i < count; i++)
        {
            temp[i + 2, 0] = mc1[i].Value.Substring(12, mc1[i].Value.Length - 12);
        }

        // Gan list Link vao mang
        for (int i = 0; i < count; i++)
        {
            temp[i + 2, 1] = "http://vnexpress.net" + mc2[i].Value.Substring(0, mc2[i].Value.Length - 21);
        }
        return temp;
    }
    protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCategory.SelectedIndex != -1 && ddlCategory.SelectedItem.Value != "")
        {
            string[,] ListTopic = GetTitleAndLinkofTopic(GetWebContent(ddlCategory.SelectedItem.Value));
            ddlTopic.Items.Clear();
            for (int i = 0; i < ListTopic.GetLength(0); i++)
            {
                ddlTopic.Items.Add(new ListItem(ListTopic[i, 0], ListTopic[i, 1]));
            }
        }
    }
}
